//
//  AvdownLoad.m
//  iNews
//
//  Created by lanou3g on 14-12-16.
//  Copyright (c) 2014年 张在青. All rights reserved.
//

#import "AvdownLoad.h"
static  AvdownLoad *Avdown = nil;
@implementation AvdownLoad
-(void)dealloc{

    [_recriverData release];
    
    [super dealloc];

}

+(AvdownLoad *)Sharedown{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Avdown = [[AvdownLoad alloc] init];
        
       // Avdown.titleArray = [NSMutableArray array];
        
    });
    return Avdown;

}



-(void)downloadinginitWithRequest:(NSString *)str_url appendPath:(NSString *)tilte{

    
    self.strTitle = tilte;
    [self aChiver:tilte];
    NSLog(@"SSS:%@",NSHomeDirectory());
    NSString *cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Cache"];
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:cachePath])
    {
        [fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if ([fileManager fileExistsAtPath:[cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_vedio.mp4",tilte]]]) {
        
        
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:nil message:@"此视频已存在" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        
        [alter show];
        
        [alter dismissWithClickedButtonIndex:0 animated:YES];
        [alter release];
    }else{
    
        //创建一个request
        NSURL *url = [NSURL URLWithString:str_url];
        NSURLRequest *request = [[[NSURLRequest alloc] initWithURL:url cachePolicy:  NSURLRequestUseProtocolCachePolicy timeoutInterval:15] autorelease];
        
        //建立网络连接
        [NSURLConnection connectionWithRequest:request delegate:self];
    
    
    }
    
    
 
    
    
}

//接收到服务器回应的时候调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

   //初始化data
    self.recriverData = [[NSMutableData alloc] init];
   

}

//接收到服务器传输数据的时候调用,此方法执行多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    [self.recriverData appendData:data];
    
//    
//    NSString *cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Cache"];
//    
//    NSString *str = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_vedio.mp4", self.strTitle]];
//    
//    //把内容写进沙盒里
//    [self.recriverData writeToFile:str atomically:YES];

}

//数据传输完成时候调用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

    
    
    NSString *cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Cache"];
    
    NSString *str = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_vedio.mp4", self.strTitle]];
    
    //判断是否下载完成
    if (self.recriverData != nil) {
        //把内容写进沙盒里
        [self.recriverData writeToFile:str atomically:YES];
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:nil message:@"下载完成" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        
        [alter show];
        
        [alter dismissWithClickedButtonIndex:0 animated:YES];
        [alter release];
        
        _flag = YES;
    }else{
    
    
        NSLog(@"11111");
    
    
    }
  
    
   


}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{


    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:nil message:@"下载失败" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    
    [alter show];
    
    [alter dismissWithClickedButtonIndex:0 animated:YES];
    [alter release];
    


}

//归档
-(void)aChiver:(NSString *)title{

    
    [self unAchiver];
    NSMutableArray *temparry;
    
    
    int t = 0;
    if (self.titleArray.count == 0) {
        //判断是否归档
        temparry = [NSMutableArray array];
    }else{
    
        temparry = [NSMutableArray arrayWithArray:self.titleArray];
        
        for (NSString *s in temparry) {
            //判断是否已经归档
            if ([s isEqualToString:title]) {
                //已经归档
                t = 1;
                break;
            }
            
            
        }
        
    }
    
    if (!t) {
        [temparry addObject:self.strTitle];
        
        NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
        
        NSLog(@"fff,%@",path);
        NSString *titlePtah = [path stringByAppendingString:@"/Private Documents/cach.plist"];
        
        [NSKeyedArchiver archiveRootObject:temparry toFile:titlePtah];
        
        self.titleArray = [NSMutableArray arrayWithArray:temparry];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"titleArray" object:nil];

    }
    
    
    
}

//反归档
-(void)unAchiver{

    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
    
    NSString *titlePtah = [path stringByAppendingString:@"/Private Documents/cach.plist"];
    
    
   NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:titlePtah];
    
    self.titleArray = array;
    
    //NSLog(@"tiotle:%@",self.titleArray);
    
}

//删除plist文件下的内容

-(void)delete:(NSString *)title{

   
    [self unAchiver];
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)[0];
    
    NSString *titlePtah = [path stringByAppendingString:@"/Private Documents/cach.plist"];
    
    if (self.titleArray.count == 0) {
        NSLog(@"没有收藏");
    }else{
    
        for (NSString *s in self.titleArray) {
            if ([s isEqualToString:title]) {
                [self.titleArray removeObject:s];
                break;
            }
        }
    
        //重新归档
        
        [NSKeyedArchiver archiveRootObject:self.titleArray toFile:titlePtah];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"titleArray" object:nil];

    }

}


@end
